package com.tjh.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * day118：Feign远程调用丢失请求头问题解决方案
 * Create by koala on 2021-05-17
 */
@Configuration
public class GuliFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){

        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //RequestContextHolder.getRequestAttributes()：可以拿到当前请求的所有属性
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

                //day118：打印线程信息
                System.out.println("RequestInterceptor线程……" + Thread.currentThread().getId());

                if(requestAttributes != null){
                    //获取当前请求对象
                    HttpServletRequest request = requestAttributes.getRequest();//老请求
                    if (request != null) {
                        //同步请求头数据，cookie
                        String cookie = request.getHeader("Cookie");
                        //给新请求同步老请求的cookie
                        template.header("Cookie",cookie);
                    }
                }

                System.out.println("feign远程之前先进行RequestInterceptor.apply");
            }
        };

    }

}
